package com.cinco.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cinco.server.mapper.MailLogMapper;
import com.cinco.server.pojo.*;
import com.cinco.server.mapper.EmployeeMapper;
import com.cinco.server.service.IEmployeeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cinco
 * @since 2022-01-11
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private MailLogMapper mailLogMapper;
    /**
     * 获取所有员工(分页)
     * @param currentPage
     * @param size
     * @param employee
     * @param beginDateScope
     * @return
     */
    @Override
    public PageResult getEmployeeByPage(Integer currentPage, Integer size, Employee employee, LocalDate[] beginDateScope) {
        Page<Employee> page = new Page<>(currentPage, size);
        IPage<Employee> iPage = baseMapper.getEmployeeByPage(page, employee, beginDateScope);
        //返回总记录数和Employee集合
        PageResult pageResult = new PageResult(iPage.getTotal(),iPage.getRecords());
        return pageResult;
    }

    /**
     * 获取工号
     * @return
     */
    @Override
    public Result maxWorkID() {
        //用max()函数获取最大的工号
        List<Map<String, Object>> maps = baseMapper.selectMaps(new QueryWrapper<Employee>().select("max(workID)"));
        //再加1转成字符串，作为最新工号
        String workID = String.format("%08d", Integer.parseInt(maps.get(0).get("max(workID)").toString())+1);
        return Result.success(null,workID);
    }

    /**
     * 添加员工
     * @param employee
     * @return
     */
    @Override
    public Result addEmp(Employee employee) {
        LocalDate beginContract = employee.getBeginContract();
        LocalDate endContract = employee.getEndContract();
        //计算合同期限：合同起始日期到合同截至日期的天数/365
        long days = beginContract.until(endContract, ChronoUnit.DAYS);
        DecimalFormat decimalFormat = new DecimalFormat("##.00");
        employee.setContractTerm(Double.parseDouble(decimalFormat.format(days/365.00)));

        if (baseMapper.insert(employee) == 1){
            Employee emp = baseMapper.getEmployee(employee.getId()).get(0);
            //数据库记录发送的消息
            String msgId = UUID.randomUUID().toString();
//            String msgId = "123456";
            MailLog mailLog = new MailLog();
            mailLog.setMsgId(msgId);
            mailLog.setEid(emp.getId());
            mailLog.setStatus(0);
            mailLog.setRouteKey(MailConstants.MAIL_ROUTING_KEY_NAME);
            mailLog.setExchange(MailConstants.MAIL_EXCHANGE_NAME);
            mailLog.setCount(0);
            //当前时间 加上 消息超时时间
            mailLog.setTryTime(LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT));
            mailLog.setCreateTime(LocalDateTime.now());
            mailLog.setUpdateTime(LocalDateTime.now());
            mailLogMapper.insert(mailLog);

            //发送消息
            //由自定义的rabbitmqTemplate检查消息是否成功发送到队列，如果成功，maillog状态干更改为1，如果失败，会由定时器MailTask执行重发操作
            rabbitTemplate.convertAndSend("MailConstants.MAIL_EXCHANGE_NAME",MailConstants.MAIL_ROUTING_KEY_NAME,emp,new CorrelationData(msgId));
            return Result.success("添加成功");
        }
        return Result.error("添加失败！");
    }

    /**
     * 更新员工
     * @param employee
     * @return
     */
    @Override
    public Result updateEmpById(Employee employee) {
        LocalDate beginContract = employee.getBeginContract();
        LocalDate endContract = employee.getEndContract();

        long days = beginContract.until(endContract, ChronoUnit.DAYS);
        DecimalFormat decimalFormat = new DecimalFormat("##.00");
        //更新合同期限
        employee.setContractTerm(Double.parseDouble(decimalFormat.format(days/365.00)));
        if(baseMapper.updateById(employee) == 1){
            return Result.success("更新成功!");
        }
        return Result.error("更新失败!");
    }

    /**
     * 查询员工数据
     * @param id
     */
    @Override
    public List<Employee> getEmployee(Integer id) {
        return baseMapper.getEmployee(id);
    }

    /**
     * 获取所有员工套账
     * @param currentPage
     * @param size
     * @return
     */
    @Override
    public PageResult getEmployeeWithSalary(Integer currentPage, Integer size) {
        //开启分页
        Page<Employee> page = new Page<>(currentPage,size);
        IPage<Employee> employeeIPage = baseMapper.getEmployeeWithSalary(page);
        PageResult pageResult = new PageResult(employeeIPage.getTotal(), employeeIPage.getRecords());
        return pageResult;
    }
}
